﻿using MS.Cache;
using MS.Entities;
using MS.Enums.Common;
using MS.Identity;
using MS.Utility.Common;
using MS.Utility.Config;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace MS.Logic
{
    public partial class MS_UserCenter_UserAccountLogic
    {

        #region 用户登录
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public LoginResult Login(string account,string password,Platform platform = Platform.BMS)
        {
            string md5Password = Utils.MD5(password.Trim());
            LoginResult loginResult = LoginResult.Success;
            MS_UserCenter_UserAccount userAccount = GetItemByQuery(x => x.Account == account.Trim()  && x.Status >= (int)UserStatus.Normal );
            if (userAccount == null || ((userAccount.Passformat==(int)Passformat.Plaintext && userAccount.Password != password ) && (userAccount.Passformat == (int)Passformat.Encrypt && userAccount.Password != md5Password)))
            {
                loginResult = LoginResult.Fail;
            }
            else
            {
                if (userAccount.Status == (int)UserStatus.Stop)
                {
                    loginResult = LoginResult.IllegalLogin;
                }
                else
                {
                    SecurityIdentity.Login(userAccount.Uid,platform);
                }
            }

            return loginResult;
        }
        #endregion

        #region 创建一个用户，用于新增或者注册
        /// <summary>
        /// 创建一个用户，用于新增或者注册
        /// </summary>
        /// <param name="userAccount"></param>
        /// <param name="userAttr"></param>
        /// <returns>返回新创建的用户uid</returns>
        public long CreateUser(MS_UserCenter_UserAccount userAccount, MS_UserCenter_UserAttr userAttr)
        {
            /*
             * 注：创建用户时要注意用户名唯一、Email唯一、电话号码唯一
             * */
            MS_UserCenter_UserAttrLogic userAttrLogic = MS_UserCenter_UserAttrLogic.GetInstance();
            if (userAccount.Passformat == (int)Passformat.Encrypt && !string.IsNullOrEmpty(userAccount.Password.Trim())) 
            {
                userAccount.Password = Utils.MD5(userAccount.Password.Trim());
            }
            if (userAccount.Uid > 0)
            {
                return userAccount.Uid;
            }
            //创建用户时需要写入两张表，因此需要开启事务
            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted }))
            {
                try
                {
                    if (!string.IsNullOrEmpty(userAccount.Account))
                    {
                        //判断Account是否唯一，若Account存在则直接返回已存在的uid
                        MS_UserCenter_UserAccount tmpUserAccount = GetItemByQuery(x => x.Account == userAccount.Account && x.Status >= (int)UserStatus.Normal);
                        if (tmpUserAccount != null)
                        {
                            return tmpUserAccount.Uid;
                        }
                    }
                    if (!string.IsNullOrEmpty(userAccount.Email))
                    {
                        //判断Email是否唯一，若Email存在则直接返回已存在的uid
                        MS_UserCenter_UserAccount tmpUserAccount = GetItemByQuery(x => x.Email == userAccount.Email && x.Status >= (int)UserStatus.Normal);
                        if(tmpUserAccount != null)
                        {
                            return tmpUserAccount.Uid;
                        }
                    }
                    if (!string.IsNullOrEmpty(userAccount.Phone))
                    {
                        //判断手机号是否唯一，若手机号存在则直接返回已存在的uid
                        MS_UserCenter_UserAccount tmpUserAccount = GetItemByQuery(x => x.Phone == userAccount.Phone && x.Status >= (int)UserStatus.Normal);
                        if (tmpUserAccount != null)
                        {
                            return tmpUserAccount.Uid;
                        }
                    }
                    Add(userAccount);
                    userAttr.Uid = userAccount.Uid;
                    userAttrLogic.Add(userAttr);
                    scope.Complete();
                }
                catch
                {
                    throw;
                }
            }
            return userAccount.Uid;
        }
        #endregion

        /// <summary>
        /// 逻辑删除用户
        /// </summary>
        /// <param name="uids"></param>
        public void Delete(List<long> uids,long loginUid)
        {
            if(uids == null || uids.Count == 0)
            {
                return;
            }
            MS_UserCenter_UserAttrLogic userAttrLogic = MS_UserCenter_UserAttrLogic.GetInstance();
            foreach(long uid in uids)
            {
                MS_UserCenter_UserAccount userAccount = GetById(uid);
                if(userAccount != null)
                {
                    userAccount.Status = (int)UserStatus.Delete;
                    userAccount.UpdateTime = DateTimeHelper.GetTime(DateTime.Now);
                    userAccount.UpdateUid = loginUid;
                    Save(userAccount);
                }
                MS_UserCenter_UserAttr userAttr = userAttrLogic.GetById(uid);
                if(userAttr != null)
                {
                    userAttr.Status = (int)UserStatus.Delete;
                    userAttr.UpdateTime = DateTimeHelper.GetTime(DateTime.Now);
                    userAttr.UpdateUid = loginUid;
                    userAttrLogic.Save(userAttr);
                }
            }
        }

        //清空LoginUser缓存
        public void RemoveCache(long uid)
        {
            //清空LoginUser缓存
            string keys = CacheConfig.LoginUserKey + uid.ToString();
            CacheAdapter.Cache.Remove(keys);
        }
    }
}
